<template>
  <view>
    <view class="flex flex-column justify-between" id="container" >
      <view>
        <view class="mt-20">
          <sub-title class="mt-20" title="基础信息"> </sub-title>
          <OrderBasicDetail :basicData="editForm" />
        </view>

        <view class="mt-20">
          <sub-title class="mt-20" title="设备信息"> </sub-title>
          <view class="p-lr-40 mb-20">
            <view class="lh-42 mt-20 flex">
              <view class="h-60 w-150 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center bg-2D8CF0 mr-20"
                @tap="chooseDevice">
                <text>选择设备</text>
              </view>
              <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center mr-50" @tap="resetDevice">
                <text>清除</text>
              </view>
            </view>
            <view class="fz-30 lh-42  mt-20 flex justify-between align-center">
              <text class="fz-32 color-FF6262 w-14">*</text><text class="w-200 color-333333 font-bold">设备名称</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="editForm.deviceName" placeholder="点击输入设备名称" height="30" input-align="right" />
              </view>
            </view>
            <view class="fz-30 lh-42 mt-20 flex justify-between align-center">
              <text class="w-200 color-333333 font-bold pl-14">设备编号</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="editForm.deviceNo" placeholder="点击输入设备编号" height="30" input-align="right" />
              </view>
            </view>
            <view class="fz-30 lh-42 mt-20 flex justify-between align-center">
              <text class="w-180 color-333333 font-bold pl-14">分组房间</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="editForm.roomName" placeholder="点击输入分组房间" height="30" input-align="right" />
              </view>
            </view>
          </view>
        </view>

        <view class="mt-20">
          <sub-title class="mt-20" title="故障内容"></sub-title>
          <view class="p-lr-40 mb-20">
            <view class="fz-30 lh-42 mt-20">
              <text class="fz-32 color-FF6262 w-14">*</text><text class="w-200 color-333333 font-bold">故障描述</text>
              <view class="mt-10 border-CCCCCC w-full pt-12 pb-20 pl-10">
                <textarea class="min-h-200 color-888888 fz-30" v-model="editForm.description" auto-height
                  placeholder="请输入故障描述" placeholder-style="color:#CCCCCC;font-size:30rpx" maxlength="200"
                  :show-confirm-bar="false" />
              </view>
            </view>

            <view class="fz-30 lh-42 mt-20 ">
              <text class="w-200 color-333333 font-bold">拍照</text>
              <view class="flex flex-wrap mt-20">

                <!-- 图片缩略图 -->
                <view class="relative mr-30" v-for="(item, index) in editForm.imageList" :key="index">
                  <image class="h-150 w-150" :data-cur="item.url" :src="item.url" @tap="previewImage" />
                  <!--  移除图片的按钮  -->
                  <view class="absolute delBtn top-0 right-0" @tap.stop="removeImage(index)">
                    <image class="h-50 w-50" src="@/static/images/workList/delPhoto.png" />
                  </view>
                </view>

                <view v-if="editForm.imageList && editForm.imageList.length < 6"
                  class="h-150 w-150 bg-CCCCCC flex align-center justify-center" @tap="uploadImage()">
                  <image class="h-50 w-50" src="@/static/images/workList/camera.png"></image>
                </view>
              </view>
            </view>

            <view class="fz-30 lh-42 mt-20 flex justify-between" @tap="chooseSender">
              <text class="fz-32 color-FF6262 w-14">*</text><text class="w-200 color-333333 font-bold">报修人</text>
              <view class="flex1 flex text-right align-center justify-end color-888888">
                <text>{{ editForm.initiator || '-fff' }}</text>
                <image v-if="initiatorIsChoose" class="w-14 h-28 ml-20" src="@/static/images/common/toPath.png"></image>
              </view>
            </view>

            <view class="fz-30 lh-42 mt-20 flex justify-between">
              <text class="w-200 color-333333 font-bold">报修时间</text>
              <view class="flex1 text-right">
                <text class="color-888888">
                  {{ editForm.createTime || '-' }}
                </text>
              </view>
            </view>
          </view>
        </view>
        <view class="mt-20" v-if="showOrderCause">
          <sub-title class="mt-20" :title="showOrderCause"></sub-title>
          <view class="p-lr-40 mb-20">
            <view class="fz-30 lh-42 mt-20">
              <text class="w-200 color-333333 font-bold">{{ showOrderCause }}</text>
              <view class="break-all mt-10">
                <text class="color-888888">{{ editForm.workOrderReason || '-' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="h-176 sticky bottom0 bg-fff flex justify-end pb-30 border-top-EEEEEE">
        <view class="mt-30 h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center mr-50" @tap="editCancel">
          <text>取消</text>
        </view>
        <view class="mt-30 h-60 w-120 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center bg-2D8CF0 mr-50" @tap="editConfirm">
          <text>确定</text>
        </view>
      </view>

    </view>

    <!-- 数据未填提示 -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="errorShow">
      <view class="h-150 flex align-center justify-center font-bold">
        <image class="mr-20 w-38 h-38" src="@/static/images/mine/error.png"></image>
        <text class="fz-30 color-333333 err-text">{{ errorContent }}</text>
      </view>
    </u-modal>

    <!--图片上传中模态框-->
    <!-- #ifndef MP-WEIXIN -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" v-model="isUploading">
      <view class="h-200 flex flex-column align-center justify-center font-bold color-888888 lh-33 bg-fff">
        <text class="mb-10">图片上传中</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-modal>
    <!-- #endif -->

    <!--微信小程序使用cover-view解决textarea层级过高问题-->

    <!-- #ifdef MP-WEIXIN -->
    <cover-view class="fixed top0 w-full min-100vh bg-00000060 flex align-center justify-center z-999"
      v-show="isUploading" @touchmove.stop.prevent="">
      <cover-view class="h-200 w-600 br-20 text-center lh-200 font-bold color-888888 lh-33 bg-fff">
        图片上传中
      </cover-view>
    </cover-view>
    <!-- #endif -->

    <!--图片加水印画板-->
    <canvas class="absolute top-99999"
            v-if="windowWidth !== 0 && windowHeight !== 0"
            :style="{'width':`${windowWidth}px`,'height': `${windowHeight}px`}"
            :canvas-id="`mycanvas`" >
    </canvas>

    <u-mask :show="isShowMask" :mask-click-able="false">
      <view class="flex justify-center align-center h-full color-fff fz-32 font-bold">
        <text>提交中...</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-mask>

    <!--是否保存缓存弹窗-->
    <u-modal v-model="saveCacheModal" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 w-full">修改未提交，是否继续退出该页面？</view>
        <view class="w-full">
          <u-checkbox-group>
            <u-checkbox
                v-model="item.checked"
                v-for="(item, index) in isCache"
                :key="index"
                :name="item.name"
            >{{item.name}}</u-checkbox>
          </u-checkbox-group>
        </view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 w-120 h-60 border-box color-fff bg-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                @tap="saveCacheConfirm">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="saveCacheCancel">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

    <!--是否使用本地缓存弹窗-->
    <u-modal v-model="isUseCacheModal" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 border-bottom-CCCCCC w-full">本地有缓存，是否使用？</view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 w-120 h-60 border-box color-fff bg-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                @tap="setCacheToEditForm">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="isUseCacheModal = false">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

  </view>
</template>

<script>
import subTitle from "@/components/SubTitle/SubTitle";
import OrderBasicDetail from "../order-basic-detail.vue";

import uploadMaskImg from "@/mixins/uploadMaskImg";
import getNavBarHeight from "@/mixins/getNavBarHeight";
import { workOrderDetail, workOrderUpdate } from "@/api/repair/workOrder"

import {mapGetters} from 'vuex'
import { REP_WORK_ORDER_STATUS } from "@/utils/dict"

export default {
  name: "RepairForm",
  components: {
    subTitle ,OrderBasicDetail
  },
  props: {
    workOrderId: {
      type: String,
      required: true
    },
  },
  mixins: [uploadMaskImg, getNavBarHeight],
  created (options) {
    this.init()
    this.isUseCacheModal = this.getFixCacheByWorkOrderId(this.workOrderId) ? true : false
  },
  data () {
    return {
      loading:false,
      isShowMask: false,
      //图片上传
      isUploading: false,
      //编辑数据
      editForm: {},
      errorContent: '',
      errorShow: false,
      saveCacheModal:false, //是否保存数据弹框
      isUseCacheModal: false, //是否使用缓存弹窗
      isCache: [{
        name: '暂存该页面信息',
        checked: true
      }],
      originData:{},
      applyCache:false,
      initiatorIsChoose:false
    }
  },
  computed: {
    ...mapGetters(['getFixCacheByWorkOrderId']),
    showOrderCause() {
      if( this.editForm.status === REP_WORK_ORDER_STATUS.REJECTED.value ){
        return '拒绝理由'
      }
      if(this.editForm.status === REP_WORK_ORDER_STATUS.SEEK_HELP.value){
        return '求助原因'
      }
      return ''
    }
  },
  methods: {
    init () {
      this.getDetail()
    },
    getDetail() {
      this.loading = true
      return workOrderDetail(this.workOrderId).then(res => {
        this.editForm = res.data
        this.initiatorIsChoose = this.editForm.initiatorUserId===-1
        this.setOriginData(res.data)
        this.loading = false
        return Promise.resolve(res)
      })
    },
    //选择人员-获取人员列表
    chooseSender () {
      if(this.initiatorIsChoose){
        uni.navigateTo({
          url: `/pages/repair/choose-initiator-user?hospitalId=${this.editForm.hospitalId}`,
          events: {
            getStaff: (data) => {
              this.editForm.initiator = data.staff.staffName
              this.editForm.initiatorUserId = data.staff.staffId
            }
          }
        })
      }
    },
    chooseDevice () {
      if (!this.editForm.hospitalId || !this.editForm.departmentId) {
        this.$u.toast('请先选择医院和科室')
        return
      }
      uni.navigateTo({
        url: `/pages/repair/choose-device?hospitalId=${this.editForm.hospitalId}&departmentId=${this.editForm.departmentId}&deviceId=${this.editForm.deviceId || ''}`,
        events: {
          confirm: (data) => {
            this.editForm.deviceId = data.deviceId
            this.editForm.deviceNo = data.deviceNo
            this.editForm.deviceName = data.deviceName
            this.editForm.roomName = data.roomName
          }
        },
      })
    },
    validate() {
      if (!this.editForm.hospitalId) {
        this.$u.toast('所属医院不能为空')
        return false
      }
      if (!this.editForm.departmentId) {
        this.$u.toast('所属科室不能为空')
        return false
      }
      if (!this.editForm.companyId) {
        this.$u.toast('负责公司不能为空')
        return false
      }
      if (!this.editForm.deviceName) {
        this.$u.toast('设备名称不能为空')
        return false
      }
      if (!this.editForm.description) {
        this.$u.toast('故障描述不能为空')
        return false
      }
      // if (!this.form.initiator) {
      //   this.$u.toast('报修人不能为空')
      //   return false
      // }
      return true
    },
    //编辑状态取消
    editCancel () {
      const keys = Object.keys(this.originData)
      let isEqual = false
      if(this.applyCache){
        const cacheData = this.getFixCacheByWorkOrderId(this.workOrderId)
        isEqual = keys.every(key=>cacheData[key]?.toString()===this.editForm[key]?.toString())
      }else{
        isEqual = keys.every(key=>this.originData[key]?.toString()===this.editForm[key]?.toString())
      }
      if(!isEqual){
        this.saveCacheModal = true
      }else{
        this.$emit('cancel')
      }
    },
    //编辑确定-提交数据
    editConfirm () {
      if (this.loading) {return}
      if (!this.validate()) {return}

      this.editForm.ossIdList = this.editForm.imageList.map(el => el.ossId).filter(el => el)
      this.isShowMask = true
      workOrderUpdate(this.editForm).then(res => {
        this.$store.dispatch('removeCacheOfWorkOrderId',this.editForm.workOrderId )
        this.isShowMask = false
        this.$emit('cancel')
      }).catch(res => {
        this.isShowMask = false
      })
    },
    // 上传图片
    uploadImage () {
      this.uploadMaskImg({sourceType: ['album', 'camera']})
    },
    //水印内容
    maskContent (ctx, image) {
      // ctx.strokeText(this.editForm.roomName, image.width * 0.092, image.width * 0.18);
      // ctx.fillText(this.editForm.roomName, image.width * 0.092, image.width * 0.18)

      // ctx.strokeText(this.$store.getters.staffName || '-', image.width * 0.092, image.width * 0.28);
      // ctx.fillText(this.$store.getters.staffName || '-', image.width * 0.092, image.width * 0.28)

      // ctx.strokeText(dayjs().format('YYYY-MM-DD HH:mm:ss'), image.width * 0.092, image.width * 0.33);
      // ctx.fillText(dayjs().format('YYYY-MM-DD HH:mm:ss'), image.width * 0.092, image.width * 0.33)
    },
    uploadSuccessCallback (data) {
      this.editForm.imageList.push({
        url: data.data.url,
        ossId: data.data.ossId,
      })
    },
    // 删除图片
    removeImage (index) {
      this.editForm.imageList.splice(index, 1)
    },
    // 点击预览
    previewImage (e) {
      const current = e.currentTarget.dataset.cur;
      const urls = this.editForm.imageList.map(el => el.url)
      uni.previewImage({
        current: current,
        urls: urls,
        indicator: "none",
      });
    },
    resetDevice() {
      this.editForm.deviceId = ''
      this.editForm.deviceName = ''
      this.editForm.deviceNo = ''
      this.editForm.roomName = ''
    },
    setCacheToEditForm(){
      const cache = this.getFixCacheByWorkOrderId(this.workOrderId)
      if(cache){
        this.editForm.deviceId = cache.deviceId
        this.editForm.deviceName = cache.deviceName
        this.editForm.deviceNo = cache.deviceNo
        this.editForm.description = cache.description
        this.editForm.imageList = JSON.parse(JSON.stringify(cache.imageList))
        this.applyCache = true
      }
      this.isUseCacheModal = false
    },
    setOriginData(data){
      this.originData.deviceId = data.deviceId
      this.originData.deviceName = data.deviceName
      this.originData.deviceNo = data.deviceNo
      this.originData.description = data.description
      this.originData.imageList = JSON.parse(JSON.stringify(data.imageList))
    },
    saveCacheConfirm(){
      const cacheData = {
        deviceId : this.editForm.deviceId,
        deviceName : this.editForm.deviceName,
        deviceNo : this.editForm.deviceNo,
        description : this.editForm.description,
        imageList : this.editForm.imageList,
      }
      this.$store.dispatch('setFixCacheOfWorkOrderId',{ id : this.editForm.workOrderId, cacheData})
      .catch((res)=>{
      })
      .finally(()=>{
        this.saveCacheModal = false
        this.$emit('cancel')
      })
    },
    saveCacheCancel(){
      this.saveCacheModal = false
      this.$emit('cancel')
    }
  }
}
</script>
<style>
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
/deep/.u-tab-bar {
  bottom: -10rpx !important;
  z-index: 9;
}

/deep/ .u-collapse-head {
  margin-bottom: 0 !important;
  border-bottom: 1px solid #ccc;
  padding: 0 !important;
  padding-bottom: 30rpx !important;
  padding-top: 20rpx !important;
}
</style>
